<template>
    <div>
        <div class="headerSty1" style="margin: 20px 0 10px;">
            <div class="headerLeftSty">
                <div class="textSty">客户签章</div>
            </div>
            <div>
                <el-form label-width="160px">
                    <el-row>
                        <el-col :span="18">
                            <el-form-item label-width="40px">
                                <div class="headerLeftSty">
                                    <div class="navSty"></div>
                                    <div class="textSty1" style="margin-left: 10px;">项目负责人</div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="一级消防注册工程师">
                                <div>{{ form.projectSaveDTO.engineerName }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="中级消防设施操作员">
                                <div>{{ form.projectSaveDTO.operatorsName }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="批准人">
                                <div>{{ form.approverName }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目负责人">
                                <div>{{ form.projectSaveDTO.projectLeaderName }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="dataForm.status <= 5">
                        <!-- 合同生成 -->
                        <el-col :span="18">
                            <el-form-item label-width="40px">
                                <div class="headerLeftSty">
                                    <div class="navSty"></div>
                                    <div class="textSty1" style="margin-left: 10px;color: rgb(90, 156, 248);">已生成合同
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="40px">
                                <div class="rickSty">
                                    <div v-html="textRich"></div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="40px">
                                <el-button class="btnAllSty" @click="clientSign">点击签章</el-button>
                                <el-button type="success" @click="clientReject">驳回</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- 签章完合同 -->
                        <el-col :span="18">
                            <el-form-item label-width="40px">
                                <div class="headerLeftSty">
                                    <div class="navSty"></div>
                                    <div class="textSty1" style="margin-left: 10px;color: rgb(90, 156, 248);">签章完合同
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="40px">
                                <div class="rickSty">
                                    <div v-html="textRichAcc"></div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="40px">
                                <!--  -->
                                <el-button type="danger" v-if="dataForm.status > 5" @click="downloadContract"
                                    :loading="btnLoading">合同附件下载</el-button>
                                <el-button type="primary" @click="submitConSignature"
                                    v-if="dataForm.status == 5">提交</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <signatureDetail v-if="signatureDetailVisible" ref="signatureDetail"
            @refreshClientSignature="refreshClientSignature">
        </signatureDetail>
        <clientReject v-if="clientRejectVisible" ref="clientReject" @clientSubReject="clientSubReject"></clientReject>
    </div>
</template>
<script>
import {
    getUserListType, getTemplatePublicList, dowRichText, downloadContractAll,
    getContractPreview, getCustomerDetail
} from "@/api/contract/contractOrg"
import { contractSignature, contractDetail, ownSendMsgCode, ownValidateCode } from "@/api/contract/contractOwn"
import { blobValidate } from "@/utils/ruoyi";
import { saveAs } from 'file-saver'
import signatureDetail from './cp/signature.vue'
import clientReject from "./cp/client-reject.vue";
export default {
    components: {
        signatureDetail,
        clientReject
    },
    props: {
        dataForm: {
            type: Object,
            default: {},
        }
    },
    data() {
        return {
            form: {
                name: ''
            },
            // 表单校验
            rules: {},
            tableData: [],
            relOptions: [],
            relAOptions: [],
            relModelOptions: [],
            // 富文本
            textRich: '',
            textRichAcc: '',
            signatureDetailVisible: false,
            clientRejectVisible: false,
            btnLoading: false
        }
    },
    created() {
        if (Object.keys(this.dataForm).length !== 0) {
            this.form = { ...this.form, ...this.dataForm }
            this.textRich = this.textRep(this.dataForm.contractRichText)
            if (this.dataForm.status > 5) {
                getContractPreview(this.dataForm.contractId).then(list => {
                    this.textRichAcc = this.textRep(list.msg)
                })
            }
        }
    },

    methods: {

        // 下载合同
        downloadContract() {
            this.btnLoading = true
            downloadContractAll(this.form.contractId).then(async data => {
                const isBlob = blobValidate(data.data);
                const filename = decodeURIComponent(data.filename);
                if (isBlob) {
                    saveAs(data.data, filename)
                } else {
                    const resText = await data.text();
                    const rspObj = JSON.parse(resText);
                    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
                    Message.error(errMsg);
                }
                this.btnLoading = false
            })
        },
        // 处理富文本
        textRep(text) {
            let updatedContent = text.replace(/<image (.*?)src="([^"]+)"(.*?)>/gi, (match, attrs, src, rest) => {
                // 检查src是否以http开头  
                if (!src.toLowerCase().startsWith('http://') && !src.toLowerCase().startsWith('https://')) {
                    // 如果不是，则拼接新的src  
                    const newSrc = `${process.env.VUE_APP_WEBSC_API}${src}`;
                    // 返回替换后的完整标签  
                    return `<image style="width: 100px; height: 60px;position: absolute;top: 50%; left: 50%; transform: translate(-50%, -50%);opacity: 0.2;" ${attrs}src="${newSrc}"${rest}>`;
                } else {
                    // 如果src以http开头，则不进行操作，直接返回原标签  
                    return match;
                }
            });

            // 第二步：给所有<td>元素添加相对定位  
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = updatedContent;
            const tds = tempDiv.getElementsByTagName('td');
            for (let i = 0; i < tds.length; i++) {
                tds[i].style.position = 'relative';
            }
            // 获取处理后的HTML字符串  
            updatedContent = tempDiv.innerHTML;
            return updatedContent;
        },
        // 提交按钮确认
        submitConSignature() {
            this.form.status = 5
            this.$nextTick(() => {
                this.$emit('refreshSignature', {...this.form, customerConfirm: 1})
            })
        },
        // 签章
        clientSign() {
            if (!this.form.projectSaveDTO.safetyResponsiblePersonPhone) {
                this.$modal.msgWarning('未填写安全负责人信息');
                return;
            }
            this.$confirm(`此操作将会向安全负责人【${this.form.projectSaveDTO.safetyResponsiblePerson}】发送一条验证码，是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const res = await ownSendMsgCode(this.dataForm.id);
                if (res.code === 200) {
                    this.$prompt('请输入验证码', '安全负责人验证', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPattern: /^\d{6}$/,
                        inputErrorMessage: '请正确输入验证码'
                    }).then(({ value }) => {
                        ownValidateCode({
                            id: this.dataForm.id,
                            verificationEnum:  'SIGN_CUSTOMER',
                            code: value
                        }).then((v) => {
                            this.signatureDetailVisible = true;
                            this.$nextTick(() => {
                                this.$refs.signatureDetail.init(this.form.contractId);
                            });
                        })
                    }).catch(() => {});
                }
            }).catch(() => { });
        },
        // 驳回
        clientReject() {
            this.clientRejectVisible = true;
            this.$nextTick(() => {
                this.$refs.clientReject.init();
            });
        },
        // 驳回确定页面
        clientSubReject(data) {
            contractSignature({
                contractId: this.form.contractId,
                status: 10,
                customerConfirm: 2,
                ...data
            }).then(res => {
                this.clientRejectVisible = false;
                this.$emit('refreshClientRejectAllDio')
            })
        },
        // 签章确定页面
        refreshClientSignature(isRefresh, data) {
            if (isRefresh) {
                contractSignature({
                    contractId: this.form.contractId,
                    status: 5,
                    customerConfirm: null,
                    ...data
                }).then(res => {
                    contractDetail(this.form.contractId).then(list => {
                        this.textRichAcc = this.textRep(list.data.contractRichText)
                    });
                })
            }
            this.signatureDetailVisible = false;
        },


    }
}
</script>

<style lang="scss" scoped>
.headerSty {
    display: flex;
    justify-content: space-between;
    width: 97%;

    .headerLeftSty {
        display: flex;
        align-items: center;

        .textSty {
            margin-left: 8px;
            font-size: 16px;
            font-weight: 700;
        }


    }

}

.headerSty1 {
    width: 97%;

    .headerLeftSty {
        display: flex;
        align-items: center;

        .textSty1 {
            margin-left: 8px;
            font-size: 14px;
            font-weight: 700;
        }

        .textSty {
            margin-left: 8px;
            font-size: 16px;
            font-weight: 600;
        }
    }

}

.rickSty {
    border: 1px solid #999;
    height: 300px;
    overflow-y: auto;
}

.btnAllSty {
    background: #7915F5;
    color: #fff;
    border: none;
}


.navSty {
    height: 15px;
    width: 5px;
    background: rgb(90, 156, 248);
}


.contSty {
    display: flex;

    .contLeftSty {
        height: 80px;
        width: 5px;
        background: rgb(90, 156, 248);
    }

    .allBlo {
        margin-left: 5px;
    }

    .LastBlockSty {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 132px;
        height: 30px;
        background: white;
        border-radius: 5px;
        color: rgb(90, 156, 248);
        border: 1px solid rgb(90, 156, 248);

        .el-icon-warning {
            color: rgb(90, 156, 248);
            font-weight: bolder;
            margin-right: 5px;
            font-size: 18px;
        }
    }

    .blockSty {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 132px;
        height: 30px;
        background: rgb(90, 156, 248);
        border-radius: 5px;
        color: white;

        .el-icon-check {
            color: white;
            font-weight: bolder;
            margin-right: 5px;
            font-size: 18px;
        }

        .el-icon-close {
            color: white;
            font-weight: bolder;
            margin-right: 5px;
            font-size: 18px;
        }
    }

    .lastTeSty {
        flex: 1;
        height: 120px;
        background: white;
        margin-left: 10px;
        border-radius: 5px;
        border: 1px solid rgb(90, 156, 248);
        overflow-y: auto;
    }
}

.text1 {
    font-size: 14px;
    font-weight: 500;
}

.text2 {
    font-size: 14px;
    color: #999;
}

.el-icon-arrow-right {
    color: rgb(90, 156, 248);
    font-weight: bolder;
    margin: 0 10px;
    font-size: 32px;
}
</style>